﻿using System;
using UnityEngine.UI;
using UnityEngine;

namespace HareGame
{
    [Serializable]
    [AddComponentMenu("UI/LocalizationText")]
    public class LocalizationText : Text
    {
        private bool m_isRegister = false;

        protected override void Start()
        {
            base.Start();
            if (GameEntry.Localization != null)
            {
                OnLocalize();
                GameEntry.Event.Register(EventID.LanguageChanged, OnLanguageChanged);
                m_isRegister = true;
            }
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();

            if (m_isRegister && GameEntry.Event != null)
                GameEntry.Event.UnRegister(EventID.LanguageChanged, OnLanguageChanged);
        }

        public string Key;

        public void ChangeKey(string key)
        {
            Key = key;
            OnLocalize();
        }

        public SystemLanguage Language = SystemLanguage.English;

        void OnLanguageChanged(int eventId, params object[] param)
        {
            OnLocalize();
        }

        void OnLocalize()
        {
            Language = GameEntry.GameData.GetObject(UserData.Language, Application.systemLanguage);
            text = GameEntry.Localization.GetValue(Key, Language);
        }
    }
}